package com.zxp.springboot.listener;

import lombok.SneakyThrows;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.Optional;

@Component
public class ServerInfoListener implements ApplicationListener<WebServerInitializedEvent> {
    private int serverPort;
    private ApplicationContext applicationContext;

    @SneakyThrows
    public String startInfo(){

        // 获取服务配置文件，name、port、以及全局服务路径
        Environment env = applicationContext.getEnvironment();
        String name = Optional.ofNullable(env.getProperty("spring.application.name")).orElse("");
        String port = env.getProperty("server.port");
        String path = Optional.ofNullable(env.getProperty("server.servlet.context-path")).orElse("");

        // 获取本地 ip 地址
        String ip = InetAddress.getLocalHost().getHostAddress();

        String info = "\n----------------------------------------------------------\n\t" +
                "Application " + name +" is running! Access URLs:\n\t" +
                "Local 访问网址: \t\thttp://localhost:" + serverPort + path + "\n\t" +
                "External 访问网址: \thttp://" + ip + ":" + port + path + "\n\t" +
                "----------------------------------------------------------";
        return info;
    };

    @Override
    public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {
        this.applicationContext = webServerInitializedEvent.getApplicationContext();
        this.serverPort = webServerInitializedEvent.getWebServer().getPort();
        System.out.println(startInfo());
    }

}

